package com.zf.yichat.service.common.shiro.helper;

import com.zf.yichat.model.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;


/**
 * 密码助手
 *
 */
@Component
public class AdminPasswordHelper {
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    private String algorithmName = "md5";
    private int hashIterations = 16;
    
    /**
     * 生成用户密码和盐
     * @param sysUser
     */
    public void encryptPassword(SysUser sysUser) {
    	if(StringUtils.isBlank(sysUser.getSalt())) {
    		sysUser.setSalt(randomNumberGenerator.nextBytes().toHex());
    	}
        String newPassword = new SimpleHash(algorithmName, sysUser.getPassword(), ByteSource.Util.bytes(sysUser.getSalt() + sysUser.getUsername()), hashIterations).toHex();
        sysUser.setPassword(newPassword);
    } 
    
    /**
     * 密码匹配器
     * @param salt
     * @param dbPassword
     * @param password
     * @return
     */
    public boolean testingPassword(String salt, String dbPassword, String password, String userName) {
    	if(StringUtils.isBlank(salt) || StringUtils.isBlank(dbPassword) || StringUtils.isBlank(password) || StringUtils.isBlank(userName)) {
    		return false;
    	}
    	String newPassword = new SimpleHash(algorithmName, password,ByteSource.Util.bytes(salt + userName),hashIterations).toHex();
    	if(StringUtils.isBlank(newPassword)) {
    		return false;
    	}
    	return dbPassword.equals(newPassword);
    }
    
    
    public static void main(String[] args) {
    	AdminPasswordHelper helper = new AdminPasswordHelper();
    	helper.randomNumberGenerator = new SecureRandomNumberGenerator();
    	
    	SysUser sysUser = new SysUser();
    	sysUser.setUsername("admin");
    	sysUser.setPassword("123456");
    	helper.encryptPassword(sysUser);
    	
    	System.out.println("passwd:" + sysUser.getPassword());
    	System.out.println("salt:" + sysUser.getSalt());
	}
}
